package cn.six1943.deepchat.module.ai.controller.admin.umodel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.six1943.deepchat.module.ai.controller.admin.provider.vo.ProviderRespVO;
import cn.six1943.deepchat.module.ai.controller.admin.provider.vo.ProviderSaveReqVO;
import cn.six1943.deepchat.module.ai.dal.dataobject.provider.ProviderDO;
import cn.six1943.deepchat.module.ai.dal.mysql.model.ModelMapper;
import cn.six1943.deepchat.module.ai.service.provider.ProviderService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.openai.services.blocking.ModelService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;

import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.six1943.deepchat.module.ai.controller.admin.umodel.vo.*;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ProviderInstDO;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ModelDO;
import cn.six1943.deepchat.module.ai.service.model.ProviderInstService;

@Tag(name = "用户 APP - 提供商")
@RestController
@RequestMapping("/app/ai/provider")
@Validated
public class AppProviderInstController {

    @Resource private ProviderInstService providerInstService;
    @Resource private ProviderService providerService;
    @Resource private ModelMapper modelMapper;

    @GetMapping("/list")
    @Operation(summary = "提供商设置-提供商列表")
    public CommonResult<List<ProviderRespVO>> getProviderList() {
        Long tenantId = TenantContextHolder.getTenantId();
        List<ProviderRespVO> providerList = providerService.getProviderList(tenantId);
        return success(providerList);
    }

    // @PutMapping("/update")
    // @Operation(summary = "更新AI提供商")
    // @PreAuthorize("@ss.hasPermission('ai:provider:update')")
    // public CommonResult<Boolean> updateProvider(@Valid @RequestBody ProviderSaveReqVO updateReqVO) {
    //     providerService.updateProvider(updateReqVO);
    //     return success(true);
    // }
    //
    // @DeleteMapping("/delete")
    // @Operation(summary = "删除AI提供商")
    // @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('ai:provider:delete')")
    // public CommonResult<Boolean> deleteProvider(@RequestParam("id") Long id) {
    //     providerService.deleteProvider(id);
    //     return success(true);
    // }

    @GetMapping("/inst/getByProvider")
    @Operation(summary = "提供商设置-获取实例")
    @Parameter(name = "providerId", description = "提供商id", required = true, example = "1024")
    public CommonResult<AppProviderInstRespVO> getByProviderId(@RequestParam("providerId") Long providerId) {
        ProviderInstDO providerInst = providerInstService.getProviderInstByProviderId(providerId);
        AppProviderInstRespVO bean = BeanUtils.toBean(providerInst, AppProviderInstRespVO.class);
        // List<ModelDO> modelDOS = modelMapper.selectListByKeyId(providerInst.getId());
        if (ObjectUtil.isNotEmpty(providerInst)) {
            List<ModelDO> modelDOS = providerInstService.getModelListByKeyId(providerInst.getId());
            bean.setModels(modelDOS);
        }
        return success(bean);
    }

    @PostMapping("/inst/verify")
    @Operation(summary = "提供商设置-校验实例密钥")
    public CommonResult<Boolean> verifyProviderInst(@Valid @RequestBody AppProviderInstUpdateReqVO reqVO) {
        try {
            providerInstService.verifyProviderInst(reqVO);
            return success(true);
        } catch (Exception e) {
            return error(960, "连接失败");
        }
    }

    @PostMapping("/inst/save")
    @Operation(summary = "提供商设置-保存实例")
    public CommonResult<Long> saveProviderInst(@Valid @RequestBody AppProviderInstUpdateReqVO reqVO) {
        // 保存、拉取模型、保存模型
        return success(providerInstService.saveProviderInst(reqVO));
    }

    @PutMapping("/inst/update-status")
    @Operation(summary = "提供商设置-启禁用实例")
    public CommonResult<Boolean> statusProviderInst(@Valid @RequestBody AppProviderInstUpdateStatusReqVO reqVO) {
        providerInstService.statusProviderInst(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @PostMapping("/inst/create")
    @Operation(summary = "提供商设置-新建提供商+实例")
    @PreAuthorize("@ss.hasPermission('ai:provider-inst:create')")
    public CommonResult<Long> createProviderInst(@Valid @RequestBody AppProviderInstSaveReqVO createReqVO) {
        return success(providerInstService.createProviderInst(createReqVO));
    }

    @DeleteMapping("/inst/delete")
    @Operation(summary = "提供商设置-删除提供商+实例")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteProviderInst(@RequestParam("id") Long id) {
        providerInstService.deleteProviderInst(id);
        return success(true);
    }

    // @GetMapping("/inst/get")
    // @Operation(summary = "获得提供商实例")
    // @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // public CommonResult<AppProviderInstRespVO> getProviderInst(@RequestParam("id") Long id) {
    //     ProviderInstDO providerInst = providerInstService.getProviderInst(id);
    //     return success(BeanUtils.toBean(providerInst, AppProviderInstRespVO.class));
    // }
    //
    // @GetMapping("/inst/page")
    // @Operation(summary = "获得提供商实例分页")
    // public CommonResult<PageResult<AppProviderInstRespVO>> getProviderInstPage(@Valid AppProviderInstPageReqVO pageReqVO) {
    //     PageResult<ProviderInstDO> pageResult = providerInstService.getProviderInstPage(pageReqVO);
    //     return success(BeanUtils.toBean(pageResult, AppProviderInstRespVO.class));
    // }
    //
    // @GetMapping("/inst/list")
    // @Operation(summary = "获得提供商实例分页")
    // public CommonResult<List<AppProviderInstRespVO>> getProviderInstList(@Valid AppProviderInstPageReqVO pageReqVO) {
    //     List<ProviderInstDO> pageResult = providerInstService.getProviderInstList(pageReqVO);
    //     return success(BeanUtils.toBean(pageResult, AppProviderInstRespVO.class));
    // }

    // ==================== 子表（模型） ====================

    // @GetMapping("/model/list-by-key-id")
    // @Operation(summary = "获得模型列表")
    // @Parameter(name = "keyId", description = "api_key")
    // public CommonResult<List<ModelDO>> getModelListByKeyId(@RequestParam("keyId") Long keyId) {
    //     return success(providerInstService.getModelListByKeyId(keyId));
    // }
    @GetMapping("/inst-model/list")
    @Operation(summary = "获得模型列表")
    public CommonResult<List<ModelDO>> getModelList() {
        return success(providerInstService.getModelList());
    }

    @PostMapping("/inst-model/create")
    @Operation(summary = "提供商设置-添加实例模型")
    @PreAuthorize("@ss.hasPermission('ai:provider-inst-model:create')")
    public CommonResult<Long> createProviderInstModel(@Valid @RequestBody AppModelSaveReqVO createReqVO) {
        return success(providerInstService.createModel(createReqVO));
    }

    @PutMapping("/inst-model/update")
    @Operation(summary = "提供商设置-修改实例模型")
    public CommonResult<Boolean> updateProviderInstMode(@Valid @RequestBody AppModelSaveReqVO createReqVO) {
        providerInstService.updateModel(createReqVO);
        return success(true);
    }

    @DeleteMapping("/inst-model/delete")
    @Operation(summary = "提供商设置-删除实例模型")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteProviderInstModel(@RequestParam("id") Long id) {
        providerInstService.deleteModel(id);
        return success(true);
    }

    @PutMapping("/inst-model/update-status")
    @Operation(summary = "提供商设置-启禁用实例模型")
    public CommonResult<Boolean> statusProviderInstModel(@Valid @RequestBody AppProviderInstUpdateStatusReqVO reqVO) {
        providerInstService.statusInstModel(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

}